import 'babel-polyfill';

import Vue from 'vue';
import VueResource from 'vue-resource';
import VueI18n from 'vue-i18n';
import VuexSaga from 'vuex-saga';

import store from './store';
import router from './routes';
import locales from './locales';

const app = {

  initialize() {
    if ("cordova" in window) {
      this.bindEvents();
    } else {
      this.setupVue();
    }
  },

  bindEvents() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this));
    document.addEventListener('backbutton', this.onBackKeyDown);
    document.addEventListener("pause", this.onPause);
    document.addEventListener("resume", this.onResume);
  },

  onDeviceReady() {
    this.setupVue();
  },

  onPause() {},

  onResume() {},

  onBackKeyDown() {},

  setupVue() {

    Vue.use(VueResource);
    Vue.use(VueI18n);

    Vue.use(VuexSaga, { store });

    let lang = window.localStorage.getItem('language');
    let browserLang = navigator.language.startsWith('en') ? 'en' : 'cn';

    const i18n = new VueI18n({
      locale: lang ? lang : browserLang,
      messages: locales,
      silentTranslationWarn: true
    });

    new Vue({
      i18n,
      store,
      router,
      template: `
        <div id="app">
          <router-view />
        </div>`
    }).$mount('#app');

  }

};

app.initialize();
